package javablackbelt.beans.factory.config;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.util.ReflectionUtils;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class Base64PropertyDecoderBeanPostProcessor extends Base64PropertyDecoderSupport 
											implements BeanPostProcessor, Serializable, Ordered {

	protected final Log logger = LogFactory.getLog(getClass());

	private int order = Ordered.LOWEST_PRECEDENCE - 1;

	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}

	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		List<Field> encodedFiels = findEncodedFields(bean.getClass());
		
		if (encodedFiels != null) {
			
			for (Field field : encodedFiels) {
				ReflectionUtils.makeAccessible(field);
				String encodedProp = (String)(ReflectionUtils.getField(field, bean));
				ReflectionUtils.setField(field, bean, new String(Base64.decode(encodedProp)));
			}
		}
		return bean;
	}

	public int getOrder() {
	  return this.order;
	}
	
	public void setOrder(int order) {
		this.order = order;
	}

}
